import React from "react";
import { useNavigate, Navigate } from "react-router-dom";
import { Form, Input, Button, message } from "antd";
import { getMenu } from "../../api";
import "./login.css";

// 定义登录表单的值类型
interface LoginFormValues {
  username: string;
  password: string;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm<LoginFormValues>(); // 创建表单实例

  // 检查本地存储中是否有 token
  if (localStorage.getItem("token")) {
    return <Navigate to="/home" replace />;
  }

  // 处理表单提交
  const handleFinish = (values: LoginFormValues) => {
    if (!values.username || !values.password) {
      return message.open({
        content: "请输入用户名或密码",
        type: "warning",
      });
    }
    getMenu(values)
      .then((res) => {
        if (res.code === 200) {
          message.success("登录成功");
          localStorage.setItem("token", res.data.token);
          navigate("/");
        } else {
          message.error("登录失败，请检查用户名和密码");
        }
      })
      .catch((error) => {
        console.error("Login failed:", error);
        message.error("登录失败，请检查用户名和密码");
      });
  };

  return (
    <Form<LoginFormValues>
      form={form}
      className="login-container"
      onFinish={handleFinish}
    >
      <div className="login_title">系统登录</div>
      <Form.Item
        label="用户名称"
        name="username"
        rules={[{ required: true, message: "请输入用户名!" }]}
      >
        <Input placeholder="请输入用户名" />
      </Form.Item>
      <Form.Item
        label="登录密码"
        name="password"
        rules={[{ required: true, message: "请输入密码!" }]}
      >
        <Input.Password type="password" placeholder="请输入密码" />
      </Form.Item>
      <Form.Item className="login-button">
        <Button type="primary" htmlType="submit">
          登录
        </Button>
      </Form.Item>
    </Form>
  );
};

export default Login;
